﻿using Ndns.ServerHost.Abstractions.Services;

namespace Ndns.CacheEventLogger
{
    class CacheEventLoggerService : ICacheEventLoggerService
    {
        private ILogger _logger;
        private ICacheService _cache;
        private int _lastRemovalCount;

        public void RegisterServices(IServiceCollection services)
        {
            _logger = services.Get<ILoggerProvider>().GetLogger<CacheEventLoggerService>();
            _cache = services.Get<ICacheService>();

            if (_cache == null)
            {
                _logger.LogWarning(string.Empty, "CacheEventLoggerService will not work because no cache service configured.");
            }
            else
            {
                _cache.AttachCompactCallback(LogCompact);
                _cache.AttachExpirationCallback(LogExpiration);
            }
        }

        private void LogCompact(int removalCount, int survivalCount)
        {
            if (_lastRemovalCount == 0 && removalCount == 0)
            {
                _logger.LogTrace(string.Empty, $"Cache compaction triggered. {removalCount} entries removed, while {survivalCount} entries remained.");
            }
            else
            {
                _logger.LogInfo(string.Empty, $"Cache compaction triggered. {removalCount} entries removed, while {survivalCount} entries remained.");
            }
            _lastRemovalCount = removalCount;

        }
        private void LogExpiration(int removalCount, int survivalCount)
        {
            if (_lastRemovalCount == 0 && removalCount == 0)
            {
                _logger.LogTrace(string.Empty, $"Removal of expired cache entries triggered. But no entries to remove. {survivalCount} entries remained.");
            }
            else if (removalCount == 0)
            {
                _logger.LogInfo(string.Empty, $"Removal of expired cache entries triggered. But no entries to remove. {survivalCount} entries remained.");
            }
            else
            {
                _logger.LogInfo(string.Empty, $"Removal of expired cache entries triggered. {removalCount} entries removed, while {survivalCount} entries remained.");
            }
            _lastRemovalCount = removalCount;
        }
    }
}
